import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../tabs/home_tab.dart';
import '../tabs/search_tab.dart';
import '../tabs/profile_tab.dart';
import 'tab_controller.dart';

class HomeScreen extends StatelessWidget {
  const HomeScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => TabControllerProvider(),
      child: const _HomeScreenContent(),
    );
  }
}

class _HomeScreenContent extends StatelessWidget {
  const _HomeScreenContent();

  @override
  Widget build(BuildContext context) {
    final tabControllerProvider = Provider.of<TabControllerProvider>(context);


    return DefaultTabController(
      length: 3,
      initialIndex: tabControllerProvider.currentIndex,
      child: Scaffold(
        body:  Builder(
          builder: (context) {
            // 获取DefaultTabController的控制器
            final TabController tabController = DefaultTabController.of(context)!;

            // 监听Provider中的变化并同步到TabController
            tabController.index = tabControllerProvider.currentIndex;

            // 监听TabController的变化并同步到Provider
            tabController.addListener(() {
              if (!tabController.indexIsChanging) {
                tabControllerProvider.currentIndex = tabController.index;
              }
            });


            final tabBarView = TabBarView(
              controller: DefaultTabController.of(context),
              physics: const NeverScrollableScrollPhysics(), // 禁止左右滑动
              children: const [
                HomeTab(),
                SearchTab(),
                ProfileTab(),
              ],
            );
            return tabBarView;
          },
        ),
        bottomNavigationBar: _buildBottomNavBar(context, tabControllerProvider),
      ),
    );
  }

  Widget _buildBottomNavBar(
      BuildContext context, TabControllerProvider tabController) {
    return BottomNavigationBar(
      currentIndex: tabController.currentIndex,
      onTap: (index) {
        tabController.currentIndex = index;
        DefaultTabController.of(context)!.animateTo(index);
      },
      items: const [
        BottomNavigationBarItem(
          icon: Icon(Icons.home),
          label: '首页',
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.search),
          label: '搜索',
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.person),
          label: '我的',
        ),
      ],
      type: BottomNavigationBarType.fixed,
      selectedItemColor: Colors.blue,
      unselectedItemColor: Colors.grey,
    );
  }
}